<?php

/**
 * 自动生成 WxEventShakeService
 * 
 * Apps/Common/Service/WxEventShakeService.class.php
 * Zix @ 2015-09-03
 */

namespace Common\Service;

class WxEventShakeService {

  private static $instance;

  const EVENT_BASE_URL = 'Wechat/Shake/index';
  
  public static function instance() {
    if (self::$instance == null) {
      $instance = new WxEventShakeService();
    }

    return $instance;
  }

  function get_default_row() {
    return array(
      'keyword' => '',
      'icon' => '',
      'name' => '',
      'title' => '',
      'rule' => '',
      'award_rule' => '',
      'start_time' => '',
      'end_time' => '',
      'daily_times' => '0',
      'total_times' => '0',
      'month_times' => '0',
      'total_active_user' => '0',
    );
  }

  function get_by_id($id) {
    $WxEventShake = M('WxEventShake');
    $data = $WxEventShake->find($id);
    return $data ? $data : array();
  }

  function get_by_cond($config) {
    $default = array(
      'wx_id' => '' ,
      'page' => 1,
      'page_size' => 6,
      'status' => '',
      'count' => FALSE,
      'order' => 'DESC',
      'sort' => 'id',
    );

    $config = extend($config, $default);

    $WxEventShake = M('WxEventShake');

    $where = array();

    if (!empty($config['status'])) {
      $where['status'] = $config['status'];
    }

    if (!empty($config['wx_id'])) {
      $where['wx_id'] = $config['wx_id'];
    }
    
    if ($config['count']) {
      return $WxEventShake->where($where)->count();
    } else {
      $order = $config['sort'] . ' ' . $config['order'];
      $limit = ($config['page'] - 1 ) * $config['page_size'] . ' , ' . $config['page_size'];
      $data = $WxEventShake
          ->where($where)
          ->limit($limit)->order($order)->select();
      //echo $WxEventShake->_sql();
      return $data ? $data : array();
    }
  }

  function get_by_keyword( $wx_id , $keyword ) {
    $WxEventShake = M('WxEventShake');
    
    $today = date('Y-m-d') ;
    $where = array(
      'wx_id' => $wx_id ,
      'keyword' => $keyword ,
      '_string' => "date_format(start_time , '%Y-%m-%d') <= '$today' and date_format(end_time , '%Y-%m-%d') >= '$today'",
    );
    
    $data = $WxEventShake->where($where)->select();
    $ret = $this->_fix_for_api($data);
    return $ret ;
  }
  
  function _fix_for_api( $arr ) {
    $ret = array();
    foreach ( $arr as $row ) {
      $ret[] = array(
     		'Title'=>$row['name'],
     		'Description'=>$row['share_desc'],
     		'PicUrl'=> U($row['icon'] , '' , TRUE , TRUE ),
     		'Url' => $row['url']
      );
    }
    return $ret;
  }
  
  function create( $data ) {
    $WxEventShake = M('WxEventShake');
    $ret = $WxEventShake->add($data);

    if ( $ret === FALSE ) {
      return ajax_arr('添加失败', FALSE);
    }
    
    $this->_after_create( $data['mer_id'] , $data['wx_id'] , $ret );
    return ajax_arr('添加成功', TRUE, array(
      'id' => $ret
    ));
  }
  
  function _after_create( $mer_id , $wx_id , $event_id ) {
    $data['url'] = $this->get_wx_oauth_url($mer_id , $wx_id, $event_id);
    $WxEventVote = M('WxEventShake');
    $WxEventVote->where('id = %d' , $wx_id )->save( $data );
  }
  
  //取活动真实 url
  function get_event_url( $mer_id , $wx_id , $event_id ) {    
    $query = array(
      'mer_id' => $mer_id ,
      'wx_id' => $wx_id ,
      'envent_id' => $event_id ,
    );
    return U( self::EVENT_BASE_URL , '' , TRUE , TRUE ) . '?' . http_build_query($query);
  }

  //微信 oauth url
  function get_wx_oauth_url( $mer_id , $wx_id , $event_id ) {
    $url = $this->get_event_url($mer_id, $wx_id, $event_id);
    
    $wechatsdk = new WechatSdkService( $mer_id , $wx_id );
    return $wechatsdk->getOauthRedirect($url); 
  }
  
  function update($id, $data) {
    $WxEventShake = M('WxEventShake');

    $ret = $WxEventShake->where("id = %d", $id)->save($data);
    if ($ret) {
      return ajax_arr('编辑成功', TRUE);
    } else {
      return ajax_arr('编辑失败', FALSE);
    }
  }

  function delete($ids) {
    $WxEventShake = M('WxEventShake');
    $ret = $WxEventShake->delete($ids);
    if ($ret == 0) {
      return ajax_arr('未删除任何数据', FALSE);
    } else if (!$ret) {
      return ajax_arr('删除失败', FALSE);
    } else {
      return ajax_arr('删除' . $ret . '行数据', TRUE);
    }
  }
  
  function do_lottery( $event_id , $user_id  , $wx_id = '' , $openid = '') {
  //检查活动是否结束
    $today = strtotime(date('Y-m-d'));
    $event_data = $this->get_by_id($event_id);
    $mer_id = $event_data['mer_id'] ;
    
    if ( $today < strtotime($event_data['start_time']) ) {
      return ajax_arr('活动还未开始');
    }
    
    if ( $today > strtotime($event_data['end_time']) ) {
      return ajax_arr('活动已经结束');
    }
    
    //判断是否设置了 用户领取总数
    $WxEventShakeUser = WxEventShakeUserService::instance();
    if ( $event_data['total_times'] > 0  ) {
      $total_count = $WxEventShakeUser->count_total_by_user( $event_id , $user_id );
      if( $total_count['amount'] >= $event_data['total_times'] ) {
        return ajax_arr('您总共只能领取 '.$event_data['total_times'] .' 次');
      }
    }

    //判断是否设置了 用户每月领取数
    if( $event_data['month_times'] > 0  ) {
      $today_count = $WxEventShakeUser->count_month_by_user($event_id , $user_id );
      if( $today_count['amount'] >= $event_data['daily_times'] ) {
        return ajax_arr('您本月只能领取 '.$event_data['month_times'] .' 次');
      }
    }
    
    //判断是否设置了 用户每日领取数
    if( $event_data['daily_times'] > 0  ) {
      $month_count = $WxEventShakeUser->count_today_by_user($event_id , $user_id  );
      if( $month_count['amount'] >= $event_data['daily_times'] ) {
        return ajax_arr('您今天只能领取 '.$event_data['daily_times'] .' 次');
      }
    }
    
    //取可用奖品
    $WxEventShakeAward = WxEventShakeAwardService::instance();
    $award_data = $WxEventShakeAward->get_by_cond(array(
      'status' => 1 ,
      'event_id' => $event_id ,
      'have_remain' => TRUE ,
      'sort' => 'rank' ,
      'order' => 'ASC' ,
    ));
    
    if ( empty( $award_data ) ) {
      return ajax_arr('奖品已经领完了');
    }
        
    //检查奖品 获得中奖率
    $new_award = array();
    foreach( $award_data as $key => $row ) {
      $award_data[$key]['take_rate'] = $row['take_rate'] > 0 ? $row['take_rate'] : $row['remain_qty'] ;
      if ( $row['take_times'] > 0 ) {
        
        //如果限制了 领取次数 就判断用户是否超过了 这个次数
        $take_count = $WxEventShakeUser->count_award_by_user( $event_id , $user_id  , $row['id'] );
        //echo $row['id'] . ':' . $row['take_times'] . '---' . $take_count['amount'] ;
        if ( $take_count['amount'] < $row['take_times'] ) {
          $new_award[] = $award_data[$key]; 
        }
      } else {
        $new_award[] = $award_data[$key]; 
      }
    }
    
    //print_r( $new_award );
    
    //取中奖奖品
    $take_award_data = $this->get_rand($new_award);
    if ( empty( $take_award_data ) ) {
      return ajax_arr('抽奖错误，请稍后再试');
    }
    $award_id = $take_award_data['id'];
    
    $ShakeUser = M('WxEventShakeUser');
    $ShakeAwardSn = M('WxEventShakeAwardSn');
        
    $ShakeUser->startTrans();
    //减少奖品数量
    $sql1 = 'update wx_event_shake set total_active_user = total_active_user + 1 where id = ' . $event_id ;
    $sql2 = 'update wx_event_shake_award set taken_qty = taken_qty + 1 , remain_qty = remain_qty - 1 where id = ' . $award_id ;
    
    $data = array(
      'mer_id' => $event_data['mer_id'] ,
      'event_id' => $event_id ,
      'user_id' => $user_id ,
      'award_id' => $award_id ,
      'award_name' => $take_award_data['name'] ,
      'ipaddress' => get_client_ip(0 , TRUE),
      'create_time' => date('Y-m-d H:i:s')
    );
    
    //$sn = rand_string(16) ;
    $ret4 = TRUE ;
    //兑换码的奖品
    if( $take_award_data['type'] == 1 ) {
      
      $sn_data = $ShakeAwardSn->where('award_id = %d and status = 0' , $award_id )->find();
      if ( empty( $sn_data ) ) {
        $ShakeUser->rollback();
        return ajax_arr('兑换码未找到');
      }
      $ret4 = $ShakeAwardSn->where('id = %d' , $sn_data['id'])->save(array(
        'status' => 1 ,
        'take_time' => date('Y-m-d H:i:s'),
      ));
      $data['award_sn'] = $sn_data['sn'] ;
    } else if ( $take_award_data['type'] == 3 ) {
      //如果是微信红包
      $WechatPay = new WechatPayService( $mer_id , $wx_id );
      $pay_ret = $WechatPay->send_redpack( $openid , $take_award_data['amount']);
      if( !$pay_ret ) {
        return ajax_arr('发送红包失败，请稍后再试');
      }
    }
    

    //更新活动状态
    $ret1 = $ShakeUser->execute( $sql1 ); 
    //echo $WxEventUser->_sql();
    //更新奖品信息
    $ret2 = $ShakeUser->execute( $sql2 );
    //添加用户参与用户
    $ret3 = $ShakeUser->add( $data );
    if ( $ret1 && $ret2 && $ret3 && $ret4 ) {
      $ShakeUser->commit();
      if( $take_award_data['type'] == 99 ) {
        $ret_text = '运气不佳啊，请再试一次';
      } else if ( $take_award_data['type'] == 3 ) {
        $ret_text = '恭喜您，抽中了红包 ' . $take_award_data['amount'] . ' 元';
      } else {
        $ret_text = '恭喜您，抽中了"' . $take_award_data['name'] . '"';
      }

      return ajax_arr( $ret_text , TRUE , array(
        'data' => $take_award_data 
      ));
    } else {      
      $ShakeUser->rollback();
      return ajax_arr('系统错误，请稍后再试');
    }
  }
  
  /**
   * 抽奖
   * @param type $pro_arr
   * @return type
   */
  function get_rand($pro_arr) {
    $result = '';
    $pro_sum = 0 ;
    //概率数组的总概率精度

    foreach ( $pro_arr as $row ) {
      $pro_sum += $row['take_rate'];
    }
    //概率数组循环

    foreach ($pro_arr as $key => $val) {
      $rand_num = mt_rand(1, $pro_sum);
      
      if ($rand_num <= $val['take_rate']) {
        $result = $pro_arr[$key];
        break;
      } else {
        $pro_sum -= $val['take_rate'] ;
      }
    }
    unset($pro_arr);
    return $result;
  }
  
  

}
